package com.ruoyi.blog.controller;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.easywenku.entity.Question;
import com.ruoyi.easywenku.entity.User;
import com.ruoyi.easywenku.service.IQuestionService;
import com.ruoyi.easywenku.service.UserService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Controller
@RequestMapping({"/adultexam", "/adultExam", "/"})
public class EasyWKController extends BaseController {


    private static final String prefix = "adultexam";
    @Autowired
    IQuestionService questionService;
    @Autowired
    UserService userService;
    private static Cache<String, Object> questionViewCache = CacheUtil.newLRUCache(1000, 1000 * 60 * 60);

    /**
     * 首页
     *
     * @param model
     * @return
     */
    @GetMapping({"/easywk"})
    public String index(Model model,
                        @RequestAttribute("userId") Long userId,
                        @RequestParam(required = false, defaultValue = "1") String current,
                        @RequestParam(required = false) String keyword,
                        @RequestParam(required = false) String course,
                        @RequestParam(required = false) String id) {
        model.addAttribute("blockType", "easywk");
        model.addAttribute("keyword", keyword);
        model.addAttribute("course", course);
        model.addAttribute("userId", userId);
        model.addAttribute("current", Long.parseLong(current));
        model.addAttribute("questionTitel", "易答文库");
        if (StrUtil.isNotEmpty(id)) {
            List<Question> list = questionService.lambdaQuery().eq(Question::getId, Long.parseLong(id)).list();
            model.addAttribute("questionList", list);
            if (list.size() > 0) {
                model.addAttribute("questionTitel", list.get(0).getQuestionBody());
            }
            return prefix + "/easywk";
        } else if (StrUtil.isNotEmpty(keyword) || StrUtil.isNotEmpty(course)) {
            List<Question> list = questionService.lambdaQuery()
                    .like(StrUtil.isNotEmpty(keyword), Question::getQuestionBody, keyword)
                    .like(StrUtil.isNotEmpty(course), Question::getCourse, course)

                    .last("limit 100").list();
            model.addAttribute("questionList", list);
            if (userId != null) {
                User byId = userService.getById(userId);
                if (byId != null) {
                    if (byId.getNumberOfSearches() != null) {
                        byId.setNumberOfSearches(byId.getNumberOfSearches() + 1);
                    } else {
                        byId.setNumberOfSearches(1);
                    }
                    userService.updateById(byId);
                }
            }

        } else {
            model.addAttribute("questionList", new ArrayList<>());
        }


        Object o = questionViewCache.get(current);
        if (o == null) {
            Page<Question> questionPage = new Page<>();
            questionPage.setCurrent(Long.parseLong(current));
            Page<Question> pageDate = questionService.lambdaQuery().orderByDesc(Question::getId).page(questionPage);
            questionViewCache.put(current, pageDate);
            model.addAttribute("questionPage", pageDate);
        } else {
            model.addAttribute("questionPage", o);
        }


        return prefix + "/easywk";
    }


    @GetMapping({"/easywk/sitemap{index}.txt"})
    @SneakyThrows
    public void easywkSitemap(@PathVariable("index") Long index, HttpServletResponse response){
        log.info("搜索引擎查询数据开始index{}",index);

        int pageSize=50000;
        List<Question> list = questionService.lambdaQuery().select(Question::getId).last("limit " + index*pageSize + ","+pageSize).list();
        PrintWriter writer = response.getWriter();
        for (Question question : list) {
            String s = "https://www.easywk.cn/easywk?id=" + question.getId();
            writer.write(s+"\n");
        }
        writer.flush();
        writer.close();
        log.info("搜索引擎查询数据结束index{}",index);
    }


}
